package geograph.china;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


/**
 * Title: 处理数据 转化成 各个对象
 * Created by Myth on 2017/8/17.
 */
public class Processor {
    private List<Province> provinceList;

    public Processor() {
        this.provinceList = new ArrayList<>();
    }

    public static void main(String[] args) throws Exception {
        String path = "src/data.txt";
        Processor processor = new Processor();
        processor.processFile(path);
        //processor.print();
        //processor.writeProvinceList("src/gen/");
        //processor.createProvinceDirAndWriteCityList("src/gen/");
    }

    public List<Province> getProvinceList() {
        return provinceList;
    }

    public Province searchProvince(String englishName) {
        for (Province province : provinceList) {
            if (province.getProvinceEnglishName().equals(englishName))
                return province;
        }
        return null;
    }

    //处理每一行数据
    private void processLine(String[] datas) {
        Province province;
        City city;
        District district;
        List<City> cityList;
        List<District> districtList;
        int provinceIndex;
        int cityIndex;

        province = new Province(datas[7], datas[6]);
        city = new City(datas[9], datas[8]);
        district = new District(datas[0], datas[2], datas[1]);
        // 在provinceList中查找 是否存在此province
        provinceIndex = provinceList.indexOf(province);
        if (provinceIndex == -1) {  // 不存在
            city.getDistrictList().add(district);
            province.getCityList().add(city);
            provinceList.add(province);
        } else { //存在
            // 获取此province的cityList
            cityList = provinceList.get(provinceIndex).getCityList();
            // 查找cityList中是否存在了city
            cityIndex = cityList.indexOf(city);
            if (cityIndex == -1) { // 不存在
                city.getDistrictList().add(district);
                cityList.add(city);
            } else { // 存在
                //获取此city的districtList,将新的district添加进去
                districtList = cityList.get(cityIndex).getDistrictList();
                districtList.add(district);
            }
        }
    }
    public void processFile(String path) throws Exception {
        File file = new File(path);
        InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(isr);
        String line;

        // 扫描数据的每一行
        while((line = bufferedReader.readLine())!=null) {
            String[] datas = line.split("\\s+");
            processLine(datas);
        }
    }

    public void print() {
        for(Province p : provinceList) {
            System.out.println("省：" + p);
            for (City city : p.getCityList()) {
                System.out.println("   市：" + city);
                for (District district : city.getDistrictList()) {
                    System.out.println("     地区：" + district);
                }
            }
        }
    }

    public <T> String getJsonArrayString(List<T> list) throws Exception {
        StringBuffer stringBuffer = new StringBuffer("[");
        int size = list.size();
        for (int i = 0; i < size - 1; i++) {
            stringBuffer.append(list.get(i).toString());
            stringBuffer.append(",");
        }
        if (size - 1 >= 0) {
            stringBuffer.append(list.get(size-1).toString());
        }
        stringBuffer.append("]");
        return stringBuffer.toString();
    }

    /**
     * 将列表信息转化成 Json数组 写入文件
     * @param fileName
     * @param list
     * @param <T>
     * @throws Exception
     */
    public <T> void writeJsonArrayToFile(String fileName, List<T> list) throws Exception {
        BufferedWriter bufferedWriter;
        File file = new File(fileName);
        if (file.createNewFile()) {
            bufferedWriter = new BufferedWriter(new FileWriter(file));
            bufferedWriter.write("[");
            int size = list.size();
            for (int i = 0; i < size - 1; i++) {
                bufferedWriter.append(list.get(i).toString());
                bufferedWriter.append(",");
            }
            if (size - 1 >= 0) {
                bufferedWriter.append(list.get(size-1).toString());
                bufferedWriter.write("]");
            }
            bufferedWriter.flush();
            bufferedWriter.close();
        }
    }

    // 将省信息写入 province_list 文件
    public void writeProvinceList(String rootDir) throws Exception {
        String fileName = rootDir + "/province_list.geograph";
        writeJsonArrayToFile(fileName, provinceList);
    }

    /**
     * 为每个省创建文件夹，并且进入文件夹为将每个省的city列表写入 city_list.geograph
     * @param rootDir
     * @throws Exception
     */
    public void createProvinceDirAndWriteCityList(String rootDir) throws Exception {
        File dir;
        String filename;
        for (Province province : provinceList) {
            dir = new File(rootDir + province.getProvinceEnglishName());
            if (dir.mkdir()) {
                filename = rootDir + province.getProvinceEnglishName() + "/" + "city_list.geograph";
                writeJsonArrayToFile(filename, province.getCityList());
                createCityDirAndWriteDistrictList(rootDir + province.getProvinceEnglishName() + "/", province.getCityList());
            }
        }
    }

    public void createCityDirAndWriteDistrictList(String rootDir, List<City> cityList) throws Exception {
        File dir;
        String filename;
        for (City city : cityList) {
            dir = new File(rootDir + city.getCityEnglishName());
            if (dir.mkdir()) {
                filename = rootDir + city.getCityEnglishName() + "/" + "district_list.geograph";
                writeJsonArrayToFile(filename, city.getDistrictList());
            }
        }
    }

}
